//
//  BuyMusicViewController.m
//  MIDI
//
//  Created by E.M.Game on 15/9/8.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "BuyMusicViewController.h"
#import "BuyMusicViewCellTableViewCell.h"
#import  "BuyMusicDetailViewViewController.h"
#import "UIViewController+NavItem.h"
#import "UIViewController+Create.h"
#import "AppConfig.h"
#import "QXNetWorkTool.h"
#import "MusicTexBookModel.h"
#import "APIAdress.h"
#import "MyOrderPayViewControl.h"
#import "SIAlertView.h"
#import "AliPayTool.h"
#import "AccountTool.h"
#import "WXApi.h"
#import "UserDataSingleton.h"
#import "MBProgressHUD+YC.h"
#import "MusicTextBookOrderModel.h"
#import "WXPrePayIdModel.h"
#import "WeChatPayTool.h"
#import "MusicTexBookDirectBuyModel.h"
#import "OperanViewController.h"
#import "MJRefresh.h"

@interface BuyMusicViewController()<UITableViewDelegate , UITableViewDataSource , UIGestureRecognizerDelegate , QXNetWorkToolDelegate , UIAlertViewDelegate , MyOrderPayViewDeletage>
@property (weak, nonatomic) IBOutlet UITableView *tabView;
@property (weak, nonatomic) IBOutlet UIView *limitView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *limitViewTopConstraint;
@property (weak, nonatomic) IBOutlet UIView *limitTopView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property(assign , nonatomic) BOOL isAnimed;
@property(assign , nonatomic) BOOL hasShowLimitView;


@property (weak, nonatomic) IBOutlet UIButton *button_group1_1;
@property (weak, nonatomic) IBOutlet UIButton *button_group1_2;
@property (weak, nonatomic) IBOutlet UIButton *button_group1_3;

@property (weak, nonatomic) IBOutlet UIButton *button_group2_1;
@property (weak, nonatomic) IBOutlet UIButton *button_group2_2;
@property (weak, nonatomic) IBOutlet UIButton *button_group2_3;
@property (weak, nonatomic) IBOutlet UIButton *button_group2_4;
@property (weak, nonatomic) IBOutlet UIButton *button_group2_5;

@property (weak, nonatomic) IBOutlet UIButton *button_group3_1;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_2;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_3;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_4;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_5;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_6;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_7;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_8;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_9;
@property (weak, nonatomic) IBOutlet UIButton *button_group3_10;

@property (assign , nonatomic) NSInteger selectIdxForGroup1;
@property (assign , nonatomic) NSInteger selectIdxForGroup2;
@property (assign , nonatomic) NSInteger selectIdxForGroup3;

@property (strong , nonatomic) NSMutableDictionary * btnDic;

@property (strong , nonatomic) NSMutableArray *itemArray;
@property (strong , nonatomic) NSMutableDictionary *majorIDDic;
@property(assign , nonatomic) int payType;
@property (strong , nonatomic) MusicTexBookModel * selectItemdata;
@property(strong , nonatomic) MusicTextBookOrderModel * orderData; //订单数据

@property(strong , nonatomic) BuyMusicViewCellTableViewCell *myCell;

@property (assign , nonatomic) NSInteger nowPage;
@property (assign , nonatomic) BOOL selectLimit;

//@property (copy , nonatomic) NSString *bookId;
//@property (copy , nonatomic) NSString *price;

@end

@implementation BuyMusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabView.dataSource = self;
    self.tabView.delegate = self;
    self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.isAnimed = NO;
    [self initUI];
    self.hasShowLimitView = NO;
    
    self.btnDic = [NSMutableDictionary dictionaryWithCapacity:18];
    [self.btnDic setObject:self.button_group1_1 forKeyedSubscript:@"101"];
    [self.btnDic setObject:self.button_group1_2 forKeyedSubscript:@"102"];
    [self.btnDic setObject:self.button_group1_3 forKeyedSubscript:@"103"];
    [self.btnDic setObject:self.button_group2_1 forKeyedSubscript:@"201"];
    [self.btnDic setObject:self.button_group2_2 forKeyedSubscript:@"202"];
    [self.btnDic setObject:self.button_group2_3 forKeyedSubscript:@"203"];
//    [self.btnDic setObject:self.button_group2_4 forKeyedSubscript:@"204"];
    [self.btnDic setObject:self.button_group2_5 forKeyedSubscript:@"205"];
    [self.btnDic setObject:self.button_group3_1 forKeyedSubscript:@"301"];
    [self.btnDic setObject:self.button_group3_2 forKeyedSubscript:@"302"];
    [self.btnDic setObject:self.button_group3_3 forKeyedSubscript:@"303"];
    [self.btnDic setObject:self.button_group3_4 forKeyedSubscript:@"304"];
    [self.btnDic setObject:self.button_group3_5 forKeyedSubscript:@"305"];
    [self.btnDic setObject:self.button_group3_6 forKeyedSubscript:@"306"];
    [self.btnDic setObject:self.button_group3_7 forKeyedSubscript:@"307"];
    [self.btnDic setObject:self.button_group3_8 forKeyedSubscript:@"308"];
    [self.btnDic setObject:self.button_group3_9 forKeyedSubscript:@"309"];
    [self.btnDic setObject:self.button_group3_10 forKeyedSubscript:@"310"];
    
    //假数据
    self.selectIdxForGroup1 = 103;
    self.selectIdxForGroup2 = 205;
    self.selectIdxForGroup3 = 310;
    
    self.majorIDDic = [[NSMutableDictionary alloc]init];
    [self.majorIDDic setValue:@"2172405d-17bb-5f40-da92-cf9cc285a980" forKey:@"1"];    //电吉他
    [self.majorIDDic setValue:@"cd12a552-95ee-9d9b-1efb-8c302c6b52c2" forKey:@"2"];   //爵士鼓
    [self.majorIDDic setValue:@"5bb9bcb5-88a0-9c85-0a15-39b51c1142be" forKey:@"3"];  //电贝司
    [self.majorIDDic setValue:@"87b65e6a-72fc-4617-d61b-351a7d080ed7" forKey:@"4"];  //音乐基础
    
    self.itemArray = [[NSMutableArray alloc]init];
    
    self.payType = -1;
    
    self.tabView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.tabView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    self.nowPage = 1;
    self.selectLimit = NO;
    
    if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].quiTa])
    {
        self.selectIdxForGroup2 = 201;
    }
    else if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].JazzDrum])
    {
        self.selectIdxForGroup2 = 202;
    }
    else if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].bass])
    {
        self.selectIdxForGroup2 = 203;
    }
    else if ([[UserDataSingleton shareInstance].currSelectExamKind isEqualToString:[UserDataSingleton shareInstance].musicBase])
    {
        self.selectIdxForGroup2 = 205;  //不限
    }
    
    [self reqData];
}

#pragma mark 设置上下拉刷新

- (void)loadNewData
{
    [self.itemArray removeAllObjects];
    
    self.nowPage = 1;
    
    [self reqData];
    [self.tabView.header endRefreshing];
}

- (void)loadMoreData
{
    ++self.nowPage;
    
    [self reqData];
    [self.tabView.footer endRefreshing];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//请求数据
-(void)reqData
{
    NSString *majorId = nil;

    if(self.selectIdxForGroup2 == 205 || self.selectIdxForGroup2 <= 200)
    {
        majorId = @"";
    }
    else
    {
        NSInteger idx = self.selectIdxForGroup2 - 200;
        NSString *key = [NSString stringWithFormat:@"%ld" , (long)idx];
        majorId = [self.majorIDDic objectForKey:key];
    }
    
    NSInteger pageNum = 10;
    NSInteger gradeNum = [self getGradeNum];
    NSInteger type = [self getType];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:majorId forKey:@"major_id"];
    [dic setValue:[NSString stringWithFormat:@"%ld" , (long)self.nowPage] forKey:@"nowpage"];
    [dic setValue:[NSString stringWithFormat:@"%ld" , (long)pageNum] forKey:@"pagenum"];
    if(gradeNum > 0 && gradeNum < 10)
    {
        [dic setValue:[NSString stringWithFormat:@"%ld" , (long)gradeNum] forKey:@"grade_num"];
    }
    
    if(type > 0 && type < 3)
    {
        [dic setValue:[NSString stringWithFormat:@"%ld" , (long)type] forKey:@"type"];
    }
    
    [dic setValue:[UserDataSingleton shareInstance].user_id forKey:@"user_id"];
    
    NSArray *arr = @[dic];
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:MusicTexBookInterface andParameter:arr tag:1];
}

-(void) configNavigationItem
{
    [self.tabBarController configNavigationBarTintColor:UIColorRGBA(0, 0, 0, 1)];
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"曲谱/教程购买";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStyleBordered target:self action:@selector(pressRight:)];
    UIFont *rightFont = [UIFont fontWithName:@"Hiragino Sans GB" size:13.0];
    UIColor *rightColor = UIColorRGBA(255, 255, 255, 1);
    
    NSDictionary * attributes = @{NSFontAttributeName:rightFont , NSForegroundColorAttributeName:rightColor };
    [rightBar setTitleTextAttributes:attributes forState:UIControlStateNormal];
    [self.navigationItem setRightBarButtonItem:rightBar];
    
}

//筛选按钮
-(void)pressRight:(UIButton *)sender
{
    if(!self.hasShowLimitView && !self.isAnimed)
    {
        [self animedShowLimitView];
    }
    else if(self.hasShowLimitView && !self.isAnimed)
    {
        [self animedHideLimitView];
        
        if (self.selectLimit)
        {
            self.nowPage = 1;
            [self.itemArray removeAllObjects];
            [self reqData];
        }
        self.selectLimit = NO;
    }
}

#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.itemArray == nil)
        return 0;
    return self.itemArray.count;
        
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.myCell) {
        return [self.myCell getHeight];
    }
    
    return 100;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myCell = [BuyMusicViewCellTableViewCell cellWithTableView:tableView];
    
    [self configCell : self.myCell row:indexPath.row];
    return self.myCell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger idx = indexPath.row;
    MusicTexBookModel * itemdata = [self.itemArray objectAtIndex:idx];
    NSString *type = itemdata.type;
    NSString * itemId = itemdata.id;
    BOOL isMusicPage = YES;
    if([type isEqualToString:@"2"])
    {
        isMusicPage = NO;
    }
    BuyMusicDetailViewViewController *ctr =[BuyMusicDetailViewViewController create];
    [ctr setData:isMusicPage data:itemId Buy:itemdata.buy];
    [self.navigationController pushViewController:ctr animated:YES];
}

#pragma mark -configCell
-(void)configCell : (BuyMusicViewCellTableViewCell *)cell row : (NSInteger)rowIdx
{
    //把购买改为详情
//    [cell.buyButton addTarget:self action:@selector(clickBuy:) forControlEvents:
//     UIControlEventTouchUpInside];
    
    [cell.buyButton setTag:rowIdx];
    
    if ([self.itemArray count] > 0)
    {    
        MusicTexBookModel *item = [self.itemArray objectAtIndex:rowIdx];
        
        NSString *tmp = [NSString stringWithFormat:@"价格: %@",item.price];
        [cell.priceLabel setText:tmp];
        [cell.itemTitle setText:item.name];
        NSString * picName = [self getPicNameBuyMajorId:item.major_id];
        [cell.itemImg setImage: [UIImage imageNamed:picName]];
        
        if ([[item type] isEqualToString:@"1"]) {
            cell.category.text = @"考级曲谱";
        } else if ([[item type] isEqualToString:@"2"]){
            cell.category.text = @"考级教程";
        }
    }
}

-(void)clickHideLimitView : (UIButton *)sender
{
    [self animedHideLimitView];
}

-(void)initUI
{
    self.limitViewTopConstraint.constant = -300;
    
    self.limitView.hidden = YES;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    //[self.view bringSubviewToFront:self.bottomView];
    //self.bottomView.userInteractionEnabled = YES;
    tapGestureRecognizer.delegate = self;
   
    tapGestureRecognizer.numberOfTapsRequired = 1;
    
    tapGestureRecognizer.numberOfTouchesRequired = 1;
    
    //tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.bottomView addGestureRecognizer:tapGestureRecognizer];
   
}
#pragma mark - GestureRecognizer
- (void)tap:(UITapGestureRecognizer *) sender
{
    [self animedHideLimitView];
    
    if (self.selectLimit)
    {
        self.nowPage = 1;
        [self.itemArray removeAllObjects];
        [self reqData];
    }
    
    self.selectLimit = NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)animedShowLimitView
{
    if(self.isAnimed || self.hasShowLimitView)
        return;
    self.limitView.hidden = NO;
    [UIView animateWithDuration:0.4 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^
     {
         CGRect orgRect = self.limitTopView.frame;
         self.limitTopView.frame = CGRectMake(0, 0, orgRect.size.width, orgRect.size.height);
         self.isAnimed = YES;
     }
    completion:^(BOOL finished)
     {
         self.isAnimed = NO;
         self.limitViewTopConstraint.constant = 0;
         self.hasShowLimitView = YES;
         [self setGroup1Btn:self.selectIdxForGroup1];
         [self setGroup2Btn:self.selectIdxForGroup2];
         [self setGroup3Btn:self.selectIdxForGroup3];
     }];
    
}

- (void)animedHideLimitView
{
    if(self.isAnimed || !self.hasShowLimitView)
        return;
    
    [UIView animateWithDuration:0.4 delay:0.1 options:UIViewAnimationOptionCurveEaseInOut animations:^
     {
         CGRect orgRect = self.limitTopView.frame;
         self.limitTopView.frame = CGRectMake(0, -300, orgRect.size.width, orgRect.size.height);
         self.isAnimed = YES;
     }
    completion:^(BOOL finished)
     {
        self.isAnimed = NO;
         self.limitViewTopConstraint.constant = -300;
         self.limitView.hidden = YES;
         self.hasShowLimitView = NO;

     }];
}


- (IBAction)limitBtnClick:(UIButton *)sender
{
    self.selectLimit = YES;
    
    NSInteger tag = sender.tag;
    if(tag > 100 && tag < 200)
    {
        [self setGroup1Btn:tag];
    }else if(tag > 200 && tag < 300)
    {
        [self setGroup2Btn:tag];
    }
    else if(tag > 300)
    {
        [self setGroup3Btn:tag];
    }
}
//从101开始
- (void)setGroup1Btn : (NSInteger)btnIndex
{
    if(btnIndex > 103)
        return;
    UIButton * btn = [self getButton:btnIndex];
    if(btn == nil)
        return;
    for(NSInteger i = 101 ; i <= 103 ; i ++)
    {
        UIButton * myBtn = [self getButton:i];
        if(myBtn != nil)
        {
            myBtn.selected = NO;
        }
    }
    self.selectIdxForGroup1 = btnIndex;
    btn.selected = YES;
}

- (void)setGroup2Btn : (NSInteger)btnIndex
{
    
    if(btnIndex > 205)
        return;
    UIButton * btn = [self getButton:btnIndex];
    if(btn == nil)
        return;
    for(NSInteger i = 201 ; i <= 205 ; i ++)
    {
        UIButton * myBtn = [self getButton:i];
        if(myBtn != nil)
        {
            myBtn.selected = NO;
        }
    }
    self.selectIdxForGroup2 = btnIndex;
    btn.selected = YES;

}

- (void)setGroup3Btn : (NSInteger)btnIndex
{
    
    if(btnIndex > 310)
        return;
    UIButton * btn = [self getButton:btnIndex];
    if(btn == nil)
        return;
    for(NSInteger i = 301 ; i <= 310 ; i ++)
    {
        UIButton * myBtn = [self getButton:i];
        if(myBtn != nil)
        {
            myBtn.selected = NO;
        }
    }
    self.selectIdxForGroup3 = btnIndex;
    btn.selected = YES;

}

- (UIButton *)getButton : (NSInteger)btnIndex
{
    NSString * key = [NSString stringWithFormat:@"%ld" , (long)btnIndex];
    UIButton * btn = [self.btnDic objectForKey:key];
    return btn;
}

//获取赛选等级
- (NSInteger)getGradeNum
{
    NSInteger num = self.selectIdxForGroup3;
    num = num - 300;
    if(num <= 0 || num >= 10)
        return -1;
    return num;
}
//获取类型：曲谱/教程
- (NSInteger)getType
{
    NSInteger num  = self.selectIdxForGroup1 - 100;
    if(num <= 0 || num >= 3)
        return  -1;
    return  num;
}

-(NSString *)getPicNameBuyMajorId : (NSString *)majorId
{
    NSString * picName = @"Img_buyMusicView_dianbeisi";
    NSInteger type = 1;
    for(int i = 1 ; i <= 4 ; i++)
    {
        NSString * key = [NSString stringWithFormat:@"%ld" , (long)i];
        NSString *myId= [self.majorIDDic objectForKeyedSubscript:key];
        if([myId isEqualToString:majorId])
        {
            type = i;
            break;
        }
    }
    switch (type) {
        case 1:
            picName = @"Img_buyMusicView_dianjita";
            break;
        case 2:
            picName = @"Img_buyMusicView_juesigu";
            break;
        case 3:
            picName = @"Img_buyMusicView_dianbeisi";
            break;
        case 4:
            picName = @"img_buyMusicView_musicBase"; 
        default:
            break;
    }
    
    return picName;
}

-(void)clickBuy : (UIButton *) sender
{
    self.selectItemdata = [self.itemArray objectAtIndex:sender.tag];
    
    if ([self.selectItemdata.buy isEqualToString:@"0"]) //未购买
    {
        MyOrderPayViewControl *obj = [MyOrderPayViewControl create];
        obj.view.backgroundColor = [UIColor clearColor];
        obj.bgImage.alpha = 1;
        
        [AccountTool saveOrderId:self.selectItemdata.id]; //曲谱教材id
        [AccountTool saveOrderPrice:self.selectItemdata.price];
        
        UIView *subView = [obj.view viewWithTag:999];
        subView.backgroundColor = [UIColor clearColor];
        
        obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        obj.definesPresentationContext = YES;
        obj.myOrderPayViewDeletage = self;
        
        [obj setTitleData:self.selectItemdata.name];
        [self presentViewController:obj animated:YES completion:nil];
    }
    else if ([self.selectItemdata.buy isEqualToString:@"1"]) //已购买，查看详情
    {
        UIAlertView * alertView = [[UIAlertView alloc]
                                   initWithTitle:@"支付成功"
                                   message:nil
                                   delegate:self
                                   cancelButtonTitle:@"取消"
                                   otherButtonTitles:@"查看",nil];
        alertView.tag = 444;
        [alertView show];
    }
}

#pragma mark -----------MyOrderPayViewDeletage--------
-(void)pay:(int)type
{
    if (type == 1) //微信
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 111;
        
        [alertView show];
    }
    else if (type == 2) //支付宝
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 222;
        
        [alertView show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 111)
    {
        //微信支付
        if (buttonIndex == 1)
        {
            self.payType = 0;
            [self WXPay];
            return;
        }
    }
    else if (alertView.tag == 222)
    {
        //支付宝支付
        if (buttonIndex == 1)
        {
            self.payType = 1;
            [self Alipay];
            return;
        }
    }
    else if (alertView.tag == 333)
    {
        //没有装微信
        return;
    }
    else if (alertView.tag == 444)
    {
        //查看详情
        
        if (buttonIndex == 1)
        {
            if (self.selectItemdata)
            {
                OperanViewController * ctr = [OperanViewController create];
                [ctr setPDFData:self.selectItemdata.file_url];
                [self.navigationController pushViewController:ctr animated:YES];
            }
        }
        
        return;
    }
}

-(void) WXPay
{
    if(![WXApi isWXAppInstalled]) // 判断 用户是否安装微信
    {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"您未安装微信，请安装后付款。"
                                  message:nil
                                  delegate:self
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil];
        
        alertView.tag = 333;
        [alertView show];
        return;
    }
    
    [self createOrder];
}

-(void) Alipay
{
    [self createOrder];
}

-(void) createOrder
{
    //生成订单
    
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
    netTools.QXNetWorkDelegate = self;
    
//    [netTools GetDataFromServerWithPostMethodandInterfaceName:MusicTexBookDirectBuyInterface andParameter:
//              @[@{
//                @"user_id":userData.user_id,
//                @"material_id":self.selectItemdata.id,
//                @"type":self.selectItemdata.type,
//                @"flag":@"0",
//                @"price":self.selectItemdata.price}] tag:2];
    

        [netTools GetDataFromServerWithPostMethodandInterfaceName:MusicTexBookOrderInterface andParameter:@[@{@"material_id":self.selectItemdata.id , @"user_id":userData.user_id , @"type":self.selectItemdata.type, @"price":self.selectItemdata.price}] tag:2];
    
}


#pragma --QuxNetTool
-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    switch (tag)
    {
        case 1:
        {
            for(NSDictionary * dic in Response)
            {
                MusicTexBookModel * item = [MusicTexBookModel MusicTexBookModelWithDict:dic];
                [self.itemArray addObject:item];
            }
            [self.tabView reloadData];
            break;
        }
        case 2:
        {
            //生成订单
//            for(NSDictionary * dic in Response)
//            {
//                MusicTexBookDirectBuyModel * item = [MusicTexBookDirectBuyModel MusicTexBookDirectBuyModelWithDict:dic];
//                self.orderData = item;
//                
//                [AccountTool saveOrderId:item.order_id];
//                
//                break;
//            }
            
            for(NSDictionary * dic in Response)
            {
                MusicTextBookOrderModel * item = [MusicTextBookOrderModel MyModelWithDict:dic];
                self.orderData = item;
                
                [AccountTool saveOrderId:item.order_id];
                
                break;
            }
            
            if (self.payType == 0)
            {
                //微信支付
                int wxPrice = [self.selectItemdata.price floatValue] * 100;
                NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
                
                //获得prepayid和noncestr
                
                [MBProgressHUD showMessage:@"正在加载" toView:self.view];
                
                QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
                
                tool.QXNetWorkDelegate = self;
                [tool GetDataFromServerWithPostMethodandInterfaceName:WXPayGetPrepayIdInterface andParameter:
                 @[@{
                       @"totalfee":strPrice,
                       @"body":self.selectItemdata.name,
                       @"outtradeno":self.orderData.order_code
                       }] tag:3];
            }
            else if (self.payType == 1)
            {
                [AccountTool savePayItem:VPayBuyMusic];
                [AccountTool savePayMusicPopToView:VPayBuyMusicPopToBuyMusicView];
                
                //支付宝支付
                [AliPayTool alipayWithOrdercode:@"" orderId:self.orderData.order_id Price:self.selectItemdata.price CityId:@"" Target:self];
            }
            
            self.payType = -1;
            break;
        }
        case 3:
        {
            for(NSDictionary * dic in Response)
            {
                WXPrePayIdModel * item = [WXPrePayIdModel WXPrePayIdModelWithDict:dic];
                
                NSString *prepayid = item.prepayid;
                NSString *noncestr = item.noncestr;
                
                int wxPrice = [self.selectItemdata.price floatValue] * 100;
                NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
                
                [AccountTool savePayItem:VPayBuyMusic];
                [AccountTool savePayMusicPopToView:VPayBuyMusicPopToBuyMusicView];
                
                //微信支付
                [WeChatPayTool WeChatWithOrdercode:@""
                                          prepayid:prepayid
                                           orderId:self.orderData.order_id
                                            Price :strPrice
                                            CityId:@""
                                          noncestr:noncestr
                                            Target:self];
                break;
            }
        }
    }
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
    switch (tag)
    {
        case 6666:
        case 7777:
        case 8888:
            [MBProgressHUD hideHUD];
            //            [MBProgressHUD showSuccess:(NSString*)message];
            break;
        default:
        {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:(NSString*)Response toView:self.view];
            break;
        }
    }
}

-(void)GetSuccessMessage:(id)message andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    switch (tag)
    {
        case 2:
            [MBProgressHUD showSuccess:(NSString*)message];
            break;
            
        case 6666:
        {
            [MBProgressHUD hideHUD];
            
            //记录成功
            if ([[AccountTool takePayResult] isEqualToString:VPaySuccess])
            {
                if (self.selectItemdata)
                {
                    UIAlertView * alertView = [[UIAlertView alloc]
                                               initWithTitle:@"支付成功"
                                               message:nil
                                               delegate:self
                                               cancelButtonTitle:@"取消"
                                               otherButtonTitles:@"查看",nil];
                    alertView.tag = 444;
                    [alertView show];
                    
                    [self reqData];
                }
            }
            
            break;
        }
        case 7777:
        case 8888:
            [MBProgressHUD hideHUD];
            [self.navigationController popViewControllerAnimated:YES];
        break;
    }
}
@end



















